package com.shop.filter;

import com.shop.pajo.LoginTicket;
import com.shop.pajo.User;
import com.shop.service.user.UserService;
import com.shop.service.user.UserServiceImpl;
import com.shop.utils.Constants;
import com.shop.utils.CookieUtil;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

public class LoginTicketFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        UserService userService = new UserServiceImpl();
        LoginTicket loginTicket = null;

        String ticket = CookieUtil.getValue(request, "ticket");
        if(ticket != null){
            loginTicket = userService.getLoginTicketByTicket(ticket);
        }

        //检查凭证是否有效
        if(loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
            //根据凭证查询用户
            User user = userService.getUserById(loginTicket.getUserId());
            //在本次请求持有用户
            session.setAttribute(Constants.USER_SESSION, user);
        }

        filterChain.doFilter(request, response);
    }
}
